<!-- 档案修改 -->
<template>
  <div class="content">
    <!-- 搜索栏 -->
    <div class="nameSearch">
      <el-input v-model="searchName" style="width: 17vw" placeholder="按编号查询" clearable>
        <template #append>
          <el-button :icon="Search" @click="getElderInfo" />
        </template>
      </el-input>
    </div>
    <!-- 表格 -->
    <el-form :model="userInfo">
      <!-- 基本信息 -->
      <div class="card">
        <el-card style="max-width: 80vw">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <div class="card-body">
            <el-form-item label="姓名">
              <el-input v-model="userInfo.baseInfo.name" />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="userInfo.baseInfo.gender" placeholder="请选择">
                <el-option value="男">男</el-option>
                <el-option value="女">女</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-date-picker v-model="userInfo.baseInfo.birthDate" type="date" placeholder="请选择" clearable />
            </el-form-item>
            <el-form-item label="婚姻">
              <el-select v-model="userInfo.baseInfo.maritalStatus" placeholder="请选择">
                <el-option value="已婚">已婚</el-option>
                <el-option value="单身">单身</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="户籍地">
              <el-input v-model="userInfo.baseInfo.domicile" />
            </el-form-item>
            <el-form-item label="民族">
              <el-input v-model="userInfo.baseInfo.nation" />
            </el-form-item>
            <el-form-item label="身份证">
              <el-input v-model="userInfo.baseInfo.idCard" disabled />
            </el-form-item>
            <el-form-item label="身高">
              <el-input v-model="userInfo.baseInfo.height">
                <template #append>cm</template>
              </el-input>
            </el-form-item>
            <el-form-item label="体重">
              <el-input v-model="userInfo.baseInfo.weight">
                <template #append>kg</template>
              </el-input>
            </el-form-item>
          </div>
        </el-card>
      </div>
      <!-- 家属信息 -->
      <div class="card">
        <el-card style="max-width: 80vw">
          <template #header>
            <div class="card-header">
              <span>家属信息</span>
            </div>
          </template>
          <div class="card-body">
            <el-form v-for="(member, index) in userInfo.familyMembers" :key="index" :model="member" label-width="auto"
              style="max-width: 60vw" class="family-member">
              <el-form-item label="姓名">
                <el-input v-model="member.name" />
              </el-form-item>
              <el-form-item label="与老人关系">
                <el-input v-model="member.relationship"> </el-input>
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="member.phone"> </el-input>
              </el-form-item>
              <!-- <el-button type="danger" @click="removeFamilyMember(index)">删除此行</el-button> -->
            </el-form>

            <!-- <el-button type="primary" @click="addFamilyMember" class="addButton">添加家属</el-button> -->
          </div>
        </el-card>
      </div>
      <!-- 健康信息 -->
      <div class="card">
        <el-card style="max-width: 80vw">
          <template #header>
            <div class="card-header">
              <span>健康信息</span>
            </div>
          </template>
          <div class="card-body">
            <el-form-item label="疾病史">
              <el-input v-model="userInfo.healthInfo.diseaseHistory" />
            </el-form-item>
            <el-form-item label="目前健康状态">
              <el-input v-model="userInfo.healthInfo.healthStatus" />
            </el-form-item>
          </div>
        </el-card>
      </div>
      <!-- 入院信息 -->
      <div class="card">
        <el-card style="max-width: 80vw">
          <template #header>
            <div class="card-header">
              <span>入院信息</span>
            </div>
          </template>
          <div class="card-body">
            <el-form-item label="入院时间">
              <el-date-picker v-model="userInfo.admissionInfo.admissionTime" type="datetime" placeholder="请选择" clearable
                disabled />
            </el-form-item>
            <el-form-item label="住处分配">
            <el-select v-model="userInfo.admissionInfo.buildingNo" placeholder="选择单元楼" style="width: 15vw">
              <el-option v-for="item in buildingOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.floorNo" placeholder="选择楼层数" style="width: 15vw">
              <el-option v-for="item in floorOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.roomNo" placeholder="选择房间号" style="width: 15vw">
              <el-option v-for="item in roomOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.bedNo" placeholder="选择床位号" style="width: 15vw">
              <el-option v-for="item in bedOptions" :key="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
          </div>
        </el-card>
      </div>
      <!-- 提交/重置按钮 -->
      <div class="finalBtn">
        <el-form-item>
          <el-button type="primary" @click="updateElderInfo"> 提交修改 </el-button>
          <el-button>取消修改</el-button>
          <el-button type="danger" @click="showDeleteDialog = true">
            删除当前用户
          </el-button>
        </el-form-item>
      </div>
      <!-- 删除用户警告弹窗 -->
      <el-dialog title="警告！！！" v-model="showDeleteDialog" width="30%" align-center>
        <span>确认删除该用户？此操作不可恢复！</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showDeleteDialog = false">取消</el-button>
            <el-button type="primary" @click="deleteCurrentUser">
              确认删除
            </el-button>
          </div>
        </template></el-dialog>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted,computed,watch } from "vue";
import { Search } from "@element-plus/icons-vue";
const showDeleteDialog = ref(false);
import { getElderInfoApi, updateElderInfoApi, deleteElderInfoApi } from "@/API/interface/checkInUpdate.ts"
import { getAllBeds } from '@/API/interface/bedManagement'
import { ElMessage } from "element-plus";
import type { UserInfo, BaseInfo, FamilyInfo, BedInfo, CheckInfo } from "@/API/interface/checkInUpdate"
const userInfo = ref<UserInfo>({
  baseInfo: {
    //基本信息
    name: "",
    gender: "",
    birthDate: new Date(), //出生日期
    domicile: "", //户籍地
    idCard: "", //身份证号
    height: "", //身高
    weight: "", //体重
    nation: "", //民族
    maritalStatus: "", //婚姻状况
  }, //基本信息
  familyMembers: [
    {
      name: "",
      relationship: "", //与本人关系
      phone: "", //联系电话
    },
  ], //家庭成员信息
  healthInfo: {
    diseaseHistory: "", //疾病史
    healthStatus: "", //目前健康状况
  }, //健康信息
  admissionInfo: {
    admissionTime: new Date(), //入院时间
    buildingNo: "", //单元楼
    floorNo: "", //楼层数
    roomNo: "", //房间号
    bedNo: "", //床位号
  }, //入院信息
});
// 楼房信息
// 一进来页面就发请求获取数据
// onMounted(async () => {
//   const res = await getAllBeds();
//   console.log("获取所有床位", res.data);

//   // 动态填充楼房、楼层、房间和床位信息
//   const uniqueBuildings = new Set<string>();
//   const uniqueFloors = new Set<string>();
//   const uniqueRooms = new Set<string>();
//   const uniqueBeds = new Set<string>();

//   res.data.data.forEach((bed: any) => {
//     uniqueBuildings.add(bed.buildingNo);
//     uniqueFloors.add(bed.floorNo);
//     uniqueRooms.add(bed.roomNo);
//     uniqueBeds.add(bed.bedNo);
//   });

//   cells.value = Array.from(uniqueBuildings).map(building => ({ value: building }));
//   floorValues.value = Array.from(uniqueFloors).map(floor => ({ value: floor }));
//   roomValues.value = Array.from(uniqueRooms).map(room => ({ value: room }));
//   bedValues.value = Array.from(uniqueBeds).map(bed => ({ value: bed }));
// });
// const cells = ref([
//   { value: '' }
// ]);
// const floorValues = ref([
//   { value: '' }
// ]);
// const roomValues = ref([
//   { value: '' }
// ]);
// const bedValues = ref([
//   { value: '' }
// ]);
const allBeds = ref<any[]>([])

// 获取所有床位数据
const getAllBed = async () => {
  const res = await getAllBeds() 
  allBeds.value = res.data.data
}

// 初始化加载数据
onMounted(() => {
  getAllBed()
})

// 楼栋选项（始终显示全部）
const buildingOptions = computed(() => {
  const buildings = new Set(allBeds.value.map(b => b.buildingNo))
  return Array.from(buildings).map(b => ({
    value: b,
    label: `${b}栋`
  }))
})

// 楼层选项（根据楼栋筛选）
const floorOptions = computed(() => {
  if (!userInfo.value.admissionInfo.buildingNo) return []
  
  const floors = new Set(
    allBeds.value
      .filter(b => b.buildingNo === userInfo.value.admissionInfo.buildingNo)
      .map(b => b.floorNo)
  )
  return Array.from(floors).map(f => ({
    value: f,
    label: `${f}层`
  }))
})

// 房间选项（根据楼栋+楼层筛选）
const roomOptions = computed(() => {
  if (!userInfo.value.admissionInfo.floorNo) return []
  
  const rooms = new Set(
    allBeds.value
      .filter(b => 
        b.buildingNo === userInfo.value.admissionInfo.buildingNo &&
        b.floorNo === userInfo.value.admissionInfo.floorNo
      )
      .map(b => b.roomNo)
  )
  return Array.from(rooms).map(r => ({
    value: r,
    label: `${r}室`
  }))
})

// 床位选项（根据楼栋+楼层+房间筛选）
const bedOptions = computed(() => {
  if (!userInfo.value.admissionInfo.roomNo) return []
  
  return allBeds.value
    .filter(b => 
      b.buildingNo === userInfo.value.admissionInfo.buildingNo &&
      b.floorNo === userInfo.value.admissionInfo.floorNo &&
      b.roomNo === userInfo.value.admissionInfo.roomNo
    )
    .map(b => ({
      value: b.bedNo,
      label: `${b.bedNo}号床`,
      disabled: b.status === 'occupied' // 可添加床位状态判断
    }))
})
// 添加家属
// const addFamilyMember = () => {
//   userInfo.value.familyMembers.push({
//     name: "",
//     relationship: "",
//     phone: "",
//   });
// };
// 删除家属信息
// const removeFamilyMember = (index: number) => {
//   userInfo.value.familyMembers.splice(index, 1);
// };
const searchName = ref("");
// 获取老人信息
const getElderInfo = async () => {
  await getElderInfoApi(searchName.value).then((res) => {
    console.log("获取老人信息返回", res.data);
    if (res.data.code == 200) {
      const backendData = res.data.data; // 后端返回的完整数据

      // 基本信息映射
      userInfo.value.baseInfo = {
        name: backendData.baseInfo?.name || '',
        gender: backendData.baseInfo?.gender || '',
        birthDate: backendData.baseInfo?.birthDate ? new Date(backendData.baseInfo.birthDate) : new Date(),
        domicile: backendData.baseInfo?.domicile || '',
        idCard: backendData.baseInfo?.idCard || '',
        height: backendData.baseInfo?.height || '',
        weight: backendData.baseInfo?.weight || '',
        nation: backendData.baseInfo?.nation || '',
        maritalStatus: backendData.baseInfo?.maritalStatus || ''
      };

      // 家属信息映射
      userInfo.value.familyMembers = backendData.familyInfo?.map((item: any) => ({
        name: item.name || '',
        relationship: item.relationship || '',
        phone: item.phone || ''
      })) || [];

      // 健康信息映射（注意字段来源）
      userInfo.value.healthInfo = {
        diseaseHistory: backendData.baseInfo?.diseaseHistory || '',
        healthStatus: backendData.baseInfo?.healthStatus || ''
      };

      // 入院信息映射（注意bedInfo结构）
      userInfo.value.admissionInfo = {
        admissionTime: backendData.baseInfo?.admissionTime ? new Date(backendData.baseInfo.admissionTime) : new Date(),
        buildingNo: backendData.bedInfo?.buildingNo || '',
        floorNo: backendData.bedInfo?.floorNo || '',
        roomNo: backendData.bedInfo?.roomNo || '',
        bedNo: backendData.bedInfo?.bedNo || '' // 注意这里用 bedNo 不是 bedId
      };

    } else {
      const error = res.data.message;
      ElMessage.error(error);
    }
  });
};
// 更新老人信息
const updateElderInfo = async () => {
  const baseInfo: BaseInfo = {
    name: userInfo.value.baseInfo.name,
    gender: userInfo.value.baseInfo.gender,
    birthDate: userInfo.value.baseInfo.birthDate,
    domicile: userInfo.value.baseInfo.domicile,
    idCard: userInfo.value.baseInfo.idCard,
    height: userInfo.value.baseInfo.height,
    weight: userInfo.value.baseInfo.weight,
    nation: userInfo.value.baseInfo.nation,
    maritalStatus: userInfo.value.baseInfo.maritalStatus,
    diseaseHistory: userInfo.value.healthInfo.diseaseHistory,
    healthStatus: userInfo.value.healthInfo.healthStatus,
    admissionTime: userInfo.value.admissionInfo.admissionTime,
  }
  const familyMembers = userInfo.value.familyMembers;
  const familyInfo: FamilyInfo[] = [];
  // 遍历 familyMembers 数组
  familyMembers.forEach((member: { name: string; relationship: string; phone: string }) => {
    familyInfo.push({
      name: member.name,
      relationship: member.relationship,
      phone: member.phone,
    });
  });
  const bedInfo: BedInfo = {
    bedNo: userInfo.value.admissionInfo.bedNo,
    buildingNo: userInfo.value.admissionInfo.buildingNo,
    roomNo: userInfo.value.admissionInfo.roomNo,
    floorNo: userInfo.value.admissionInfo.floorNo,
  };
  const checkInfo: any = {
    checkInfo: {
      baseInfo: baseInfo,
      familyInfo: familyInfo,
      bedInfo: bedInfo,
      elderId: searchName.value,
    }

  };
  console.log("修改后的信息", checkInfo);
  const res = await updateElderInfoApi(checkInfo);
  console.log("修改后返回", res);
  if (res.data.code === 200) {
    ElMessage.success("修改成功");
    //清空表单
    userInfo.value = {
      baseInfo: {
        name: "",
        gender: "",
        birthDate: new Date(),
        domicile: "",
        idCard: "",
        height: "",
        weight: "",
        nation: "",
        maritalStatus: "",
      },
      familyMembers: [],
      healthInfo: {
        diseaseHistory: "", //疾病史
        healthStatus: "", //目前健康状况
      }, //健康信息
      admissionInfo: {
        admissionTime: new Date(), //入院时间
        buildingNo: "", //单元楼
        floorNo: "", //楼层数
        roomNo: "", //房间号
        bedNo: "", //床位号
      }, //入院信息
    }
  } else {
    ElMessage.error("修改失败");
  }
};
// 删除老人信息
const deleteCurrentUser = async () => {
  await deleteElderInfoApi(searchName.value).then(
    (res) => {
      console.log("删除老人信息反馈", res.data);
      ElMessage.success("删除成功");
      //清空表单
      userInfo.value = {
        baseInfo: {
          name: "",
          gender: "",
          birthDate: new Date(),
          domicile: "",
          idCard: "",
          height: "",
          weight: "",
          nation: "",
          maritalStatus: "",
        },
        familyMembers: [],
        healthInfo: {
          diseaseHistory: "", //疾病史
          healthStatus: "", //目前健康状况
        }, //健康信息
        admissionInfo: {
          admissionTime: new Date(), //入院时间
          buildingNo: "", //单元楼
          floorNo: "", //楼层数
          roomNo: "", //房间号
          bedNo: "", //床位号
        }, //入院信息
      }
      searchName.value=''
    }
  ).catch(
    (error) => {
      console.log("删除失败", error);
      ElMessage.error("删除失败");
    }
  )
  showDeleteDialog.value = false
}
</script>

<style lang="less" scoped>
.nameSearch {
  margin: 1vh 0;
}

.card {
  margin-top: 1vw;

  .card-header {
    font-size: 1.5em;
    font-weight: bold;
    color: #409eff;
  }

  .el-card /deep/ .el-card__header {
    padding: 1vw;
  }

  .card-body {
    //所有子项目的长度限定
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .el-form-item {
      width: 20%;
      margin: 1vh 1vw;
    }

    .family-member {
      display: flex;
      align-items: center;
    }

    .addButton {
      margin-left: -11vw;
    }
  }

  .el-card /deep/ .el-card__body {
    padding: 0.5vw;
  }
}

.finalBtn {
  display: flex;
  margin-left: 30vw;
  margin-top: 1vw;
}
</style>